<?php

namespace app\admin\controller;

use app\admin\model\HelpTab as HelpTabModel;
use app\admin\validate\CommonnValidate;
use app\admin\validate\PhotoValidate;
use app\BaseController;

class HelpTab extends BaseController
{
    protected $middleware = ['Auth'];
    public function allList()
    {
        $params = $this->request->post(['name']);
        $sql = new HelpTabModel();
        $whereArr = [];
        if(isset($params['name']) && $params['name']) {
            $whereArr[] = ["name", "LIKE", '%'.$params['name'].'%'];
        }
        $list = $sql->where($whereArr) ->order('sort desc')
            ->order('create_at desc')->select();
        return result()->success($list);
    }

    public function addEdit() {
        $params = $this->request->post(['id']);
        if(isset($params['id']) && $params['id']) {
            return $this->edit();
        }
        return $this->add();
    }

    public function add() {
        $params = $this->request->post(['name', 'sort']);
        $validate = new PhotoValidate();
        if (!$validate->scene('addHelpTab')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new HelpTabModel();
        $info = $sql->where('name', $params['name'])->findOrEmpty();
        if(!$info->isEmpty()) {
            return result()->fail("分类已存在", 1);
        }
        $sql->save($params);
        return result()->success("添加成功");
    }

    public function edit() {
        $params = $this->request->post(['id', 'name', 'sort']);
        $validate = new CommonnValidate();
        if (!$validate->scene('edit')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new HelpTabModel();
        $info = $sql->find($params['id']);
        $info->save($params);
        return result()->success("修改成功");
    }

    public function dels() {
        $params = $this->request->post(['ids']);
        $validate = new CommonnValidate();
        if (!$validate->scene('dels')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new HelpTabModel();
        $sql->destroy($params['ids']);
        return result()->success("删除成功");
    }
}